import { defineStore } from 'pinia'
import { http } from '../utils/http'
import { ElMessage } from 'element-plus'

export const useTaskStore = defineStore('task', {
  state: () => ({
    userTasks: []
  }),

  getters: {
    getTaskById: (state) => (taskId) => {
      return state.userTasks.find(task => task.id === taskId)
    },
    
    pendingTasks: (state) => {
      return state.userTasks.filter(task => task.status === 'pending')
    },
    
    inProgressTasks: (state) => {
      return state.userTasks.filter(task => task.status === 'in_progress')
    },
    
    completedTasks: (state) => {
      return state.userTasks.filter(task => task.status === 'completed')
    }
  },

  actions: {    
    async fetchTasks() {
      try {
        const response = await http.get('/tasks/my-tasks')

        if (response?.data?.userTasks) {
          this.userTasks = response.data.userTasks.map(userTask => ({
            ...userTask,
            reward: typeof userTask.reward === 'string' ? JSON.parse(userTask.reward) : userTask.reward
          }))
        }
      } catch (error) {
        console.error('获取任务列表失败:', error)
        ElMessage.error('获取任务列表失败')
        throw error
      }
    },

    async startTask(taskId) {
      try {
        // 检查任务是否已存在
        const existingTask = this.getTaskById(taskId)
        if (existingTask) {
          if (existingTask.status === 'completed') {
            throw new Error('该任务已完成')
          }
          if (existingTask.status === 'in_progress') {
            throw new Error('该任务已在进行中')
          }
        }

        const response = await http.post(`/tasks/${taskId}/start`)
        if (response?.data?.task) {
          const updatedTask = {
            ...response.data.task,
            status: 'in_progress',
            progress: 0
          }
          
          // 如果任务已存在，更新它；否则添加到列表
          if (existingTask) {
            this.userTasks = this.userTasks.map(task => 
              task.id === taskId ? updatedTask : task
            )
          } else {
            this.userTasks.push(updatedTask)
          }
          
          return updatedTask
        }
      } catch (error) {
        console.error('开始任务失败:', error)
        ElMessage.error(error.message || '开始任务失败')
        throw error
      }
    },

    async updateTaskProgress(taskId, progress) {
      try {
        const task = this.getTaskById(taskId)
        if (!task) {
          throw new Error('任务不存在')
        }
        
        if (task.status !== 'in_progress') {
          throw new Error('只能更新进行中的任务进度')
        }

        const response = await http.put(`/tasks/${taskId}/progress`, { progress })
        if (response?.data?.userTask) {
          this.userTasks = this.userTasks.map(task => 
            task.id === taskId 
              ? { ...task, ...response.data.userTask }
              : task
          )
          if (response.data.userTask.isCompleted) {
            ElMessage.success('任务完成！')
          } else {
            ElMessage.success('任务进度已更新')
          }
        }
      } catch (error) {
        const errorMessage = error.message || '更新任务进度失败'
        ElMessage.error(errorMessage)
        throw error
      }
    },

    async completeTask(taskId) {
      try {
        const task = this.getTaskById(taskId)
        if (!task) {
          throw new Error('任务不存在')
        }

        const response = await http.post(`/tasks/${taskId}/complete`)
        if (response?.data?.userTask) {
          // 更新任务状态
          this.userTasks = this.userTasks.map(task => 
            task.id === taskId 
              ? { 
                  ...task, 
                  ...response.data.userTask,
                  status: 'completed',
                  completedAt: new Date()
                }
              : task
          )

          // 显示奖励信息
          const rewards = response.data.rewards
          if (rewards) {
            ElMessage.success(`任务完成！获得 ${rewards.experience} 经验`)
          } else {
            ElMessage.success('任务完成！')
          }

          return response.data
        }
      } catch (error) {
        console.error('完成任务失败:', error)
        ElMessage.error(error.message || '完成任务失败')
        throw error
      }
    }
  }
}) 